package com.example.nuc_ms_beta.ui.viewcomponent.slidmenuview;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.nuc_ms_beta.R;
import com.example.nuc_ms_beta.ui.viewcomponent.viewpager.ViewPagerItem;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by 张博川 on 2016/9/30. 滚动图（目标将请求数据通过外层注入）
 */
public class SlideViewPager extends FrameLayout {
    private final static int IMAGE_COUNT = 5;
    private final static int TIME = 3;
    private final static boolean isAutoPlay = true;
    private String[] imageUrls;
    private List<ImageView> imageViews;
    private List<View> pointViewLists;
    private ViewPager viewPager;
    private int CurrentPageNumber = 0;
    private ScheduledExecutorService scheduledExecutorService;
    private Context context;
    private List<ViewPagerItem> pagers;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(CurrentPageNumber);
        }
    };


    public SlideViewPager(Context context) {
        this(context, null);
    }

    public SlideViewPager(Context context, AttributeSet attr) {
        this(context, attr, 0);
    }

    public SlideViewPager(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        //      initImageLoader(context);
        initDate("wwwwwwwwwwwwwwwwwwww");

        if (isAutoPlay) {
            startPlay();
        }
    }

    private void initDate(String wwwwwwwwwwwwwwwwwwww) {
        imageViews = new ArrayList<ImageView>();
        pointViewLists = new ArrayList<View>();
        //请求网络//调用InitUI(Context context);
    }

    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }

    private void StopPlay() {
        scheduledExecutorService.shutdown();
    }

    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            synchronized (viewPager) {
                CurrentPageNumber = (CurrentPageNumber + 1) % imageViews.size();
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    private void initUI(Context context) {
        if (imageUrls == null || imageUrls.length == 0) return;
        View view = LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);
        LinearLayout doLayout = (LinearLayout) view.findViewById(R.id.dotLayout);
        doLayout.removeAllViews();

        for (int i = 0; i < imageUrls.length; i++) {
            ImageView imageView = new ImageView(context);
            imageView.setTag(imageUrls[i]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageViews.add(imageView);


            ImageView dotView = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 4;
            params.rightMargin = 4;
            doLayout.addView(dotView, params);
            pointViewLists.add(dotView);
        }
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        //viewPager.setFocusable(true);
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPagerChangeListener());
    }

    /*
    @张博川 myViewPagerAdapter
     */
    private class MyPagerAdapter extends PagerAdapter {
        //获取所有图片的个数
        @Override
        public int getCount() {
            return imageViews.size();
        }

        //判断是否是一个图片
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        //ViewPager自身只能缓存3张图片。超出的范围会自动销毁。
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViews.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = imageViews.get(position);
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里设置点击事件
                }
            });
            container.addView(imageViews.get(position));
            return imageViews.get(position);
        }
    }

    /*
    监听器 onPageChangeListener()
     */
    private class MyPagerChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPaly = false;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case 1:
                    isAutoPaly = false;
                    break;
                case 2:
                    isAutoPaly = true;
                    break;
                case 0://滑动结束
                    //最后一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter()
                            .getCount() - 1 && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager
                                .setCurrentItem(viewPager.getAdapter().getCount() - 1);
                    }
                    break;

            }
        }
    }
}
